package cn.schoolwow.quickdao.module.database.ddl.query.flow.index.getSingleEntityIndexFlow;

import cn.schoolwow.quickdao.annotation.IndexType;
import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.database.ddl.IndexField;
import cn.schoolwow.quickdao.module.database.parent.domain.ResultSetConsumer;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.sql.ResultSet;
import java.util.Arrays;

public class GetSingleEntityIndexByMySQLFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        String tableName = (String) flowContext.checkData("tableName");
        String indexName = (String) flowContext.checkData("indexName");
        flowContext.startFlow(new ExecuteQueryConnectionFlow())
                .putTemporaryData("sql", "select table_name, index_name, non_unique, column_name, index_type, index_comment from information_schema.`statistics` where table_schema = '" + quickDAOConfig.databaseContext.databaseName + "' and table_name = ? and index_name = ?;")
                .putTemporaryData("parameters", Arrays.asList(tableName, indexName))
                .putReturnData("resultSetConsumer",new ResultSetConsumer() {
                    @Override
                    public void consumeResultSet(ResultSet resultSet) throws Exception {
                        IndexField indexField = null;
                        while (resultSet.next()) {
                            if (null == indexField) {
                                indexField = new IndexField();
                                indexField.indexType = resultSet.getInt("non_unique") == 0 ? IndexType.UNIQUE : IndexType.NORMAL;
                                if ("FULLTEXT".equals(resultSet.getString("index_type"))) {
                                    indexField.indexType = IndexType.FULLTEXT;
                                }
                                indexField.indexName = resultSet.getString("index_name");
                                indexField.columns.add(resultSet.getString("column_name"));
                                indexField.using = resultSet.getString("index_type");
                                indexField.comment = resultSet.getString("index_comment");
                            } else {
                                indexField.columns.add(resultSet.getString("column_name"));
                            }
                        }
                        flowContext.putData("indexField", indexField);
                    }
                })
                .execute();
    }

    @Override
    public String name() {
        return "获取数据库单个表的索引信息-MySQL";
    }
}
